# coding=utf-8
import base64
import datetime
import hashlib
import hmac
import json
import logging
import traceback
from urllib import parse
import urllib
import time
import pymysql
import requests
from time import strftime, localtime

def local_time():
    return strftime("%Y-%m-%d %H:%M:%S", localtime())

def __dingtalk_robot_signature(secret):
    # 当前时间戳
    timestamp = int(round(time.time() * 1000))
    # 密钥
    secret_enc = secret.encode('utf-8')

    # 加签
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    # 签名加密
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    return timestamp, sign

def dingtalk_robot(content, atMobiles, isAtAll):
    """
    钉钉群机器人
    :param content: 要发送的内容
    :param atMobiles: 指定艾特的人
    :param isAtAll: 是否艾特全部？
    :return:
    """
    secret = 'SECee1ca196b574641b58ccc340b8253e2639d8f94b6d300daeb4612d817982e0ff'
    token = '792703a83a8a2d1a3404da75ba8d1302e922e75c9ea9ce8dcdeedbebedfe98b6'
    # 获取钉钉群机器人🤖签名.
    signature = __dingtalk_robot_signature(secret)
    timestamp = signature[0]
    sign = signature[1]
    url = "https://oapi.dingtalk.com/robot/send?access_token={}&timestamp={}&sign={}".format(token, timestamp, sign)
    headers = {
        "Content-Type": "application/json"
    }

        # contentdata = '亚马逊广告采集脚本异常结束\n开始时间：{}，\n结束时间：{}，\n总任务数：{}，\n总结果数：{}。\n，剩余任务数：{}。\n检查脚本日志，查看报错'.format(content['start_time'], content['end_time'], content['start_task'], content['result_count'], content['last_task'])
    contentdata = content
    body = {
        "msgtype": "text",
        "text": {"content": contentdata},
        "at": {"atMobiles": atMobiles, "isAtAll": isAtAll}
    }

    res = requests.post(url=url, headers=headers, data=json.dumps(body))
    print(res)
    print(res.text)

if __name__ == '__main__':
    dingtalk_robot('爬虫出现数据库链接错误',['13954358641'],False)